package com.gym.controller.action.admin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.gym.controller.form.admin.UpdateTrainerForm;
import com.gym.model.dao.ConnessioneException;
import com.gym.model.dao.DAOTrainer;
import com.gym.model.dao.DatoNonTrovatoException;
import com.gym.model.dao.MetodoDaoException;
import com.gym.model.dao.ViolazioneIntegritaException;
import com.gym.model.entity.Trainer;

public class UpdateTrainer extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		UpdateTrainerForm f = (UpdateTrainerForm) form;
		
		String trainerfirstname = f.getTrainerfirstname();
		String trainerlastname = f.getTrainerlastname();
		String trainerphone = f.getTrainerphone();
		String traineremail = f.getTraineremail();
		String trainerskill = f.getTrainerskill();
		String trainernote = f.getTrainernote();
		
		int id = Integer.parseInt(request.getParameter("id"));
		
		Trainer trainer = new Trainer(id, trainerfirstname, trainerlastname, trainerphone, traineremail, trainerskill, trainernote);
		
		try {
			DAOTrainer dao = new DAOTrainer();
			dao.update(trainer);
			
			request.setAttribute("feedback", "OK, modificato il trainer "+trainerfirstname+" "+trainerlastname);
			
			return mapping.findForward("success");
			
		} catch (ConnessioneException | MetodoDaoException | DatoNonTrovatoException | ViolazioneIntegritaException e) {
			request.setAttribute("error", e.getMessage());
			return mapping.findForward("failure"); 
		}
		
	}
	
}
